import Nav from '../../src/components/common/nav/nav.vue'
import {ApiUrl,Islogined,returnId,show,hide,textLengthFormatter} from './ApiUrl.js'
import loading from '../../src/components/common/loading/loading.vue'
import fangerror from '../../src/components/common/fangerror/fangerror.vue'
import Swiper from '../plugins/swiper4x/swiper.min'
import {phasesData} from '../plugins/mui/mater.data'
import Vue from 'vue'
import VueScroller from 'vue-scroller'
Vue.use(VueScroller)

export default {
  components: {
    meun:Nav,loading,fangerror,
  },
  data(){
    return {
      FangLoading:false,//Loading控制，true显示，false不显示
      fangerroring:false,//提示文本弹窗，true显示，false不显示
      fangerrorText:'',//提示文本弹窗内容
      headerTitle:'指标详情',
      contentTitle:'车站',
      subStatus: false,  //顶部收藏
      noDataShow:[true,true,true,true],   //无数据时的展示
      noDataText:'暂无数据...',   //无数据时的展示
      materialsData:[],  //接收数据数组
      contentData:[],  //接收数据数组
      slideData:[],  //接收数据数组
      featuresLength:[],  //接收数据数组
      contentLength:[],  //接收数据数组
      chooseDateArr:[],  //接收数据数组
      slideArr:[],  //接收数据数组
      radarData:[],  //接收数据数组
      count:1,
      slidePage:1,   //滑块页码
      featuresPage:1,   //主材特征页码
      contentPage:1,   //主材含量页码
      synId:null, //综合指标id
      dateIndex:'',  //日期下标
      startDate:'',
      endDate:'',
      ids:'',
    }
  },
  beforeDestroy(){  //实例销毁之前调用
    window.removeEventListener('resize',this.chartResize);  //移除监听事件
  },
  mounted() {
    this.lineChart();  //曲线图
    let _This = this;
    // let windowH = $(window).height();
    // let meunBoxH = $('.meunBox').outerHeight(true);
    // let megessBoxH = $('.megessBox').outerHeight(true);
    // $('.contentLeft,.contentRight').height( windowH - meunBoxH - megessBoxH );
    // $('.tab_box').height(windowH - meunBoxH);
  },
  methods:{
    setTimeoutError:function () {
      setTimeout(() => {
        $('.Fang_errorBox').hide();
        this.fangerroring = false
      }, 2000)
    },
    chartResize : function () {  //图表自适应
      let _This = this;
      setTimeout(function () {
        _This.LineChart.resize();
        _This.raChart.resize();
      }, 200)
    },
    postSlideData:function (fn) {
      let _This = this;
      _This.ids = this.$route.query.id;   //获取首页传过来的参数
      let params = {
        page:_This.slidePage,
        pageSize:2,
        indexSubscriptionId:_This.ids,
        extendInfo:true,
        subStatus:true
      };
      _This.slideAjax(params,function (data) {
        _This.slideData = data;
        fn(data);  //传swiper初始化函数
      })
    },
    chooseDate:function(){   //日期弹窗
      let _This = this;
      if(this.chooseDateArr == '' || this.chooseDateArr == null){
        _This.fangerroring = true;  //提示
        _This.fangerrorText = '暂无数据';
        _This.setTimeoutError();
      }else {
        let picker = new mui.PopPicker();
        picker.setData(this.chooseDateArr);
        // picker.pickers[0].setSelectedIndex(index,store);//设置默认值得下标和内容。
        picker.show(function(items) {  //弹窗回调(点击确定按钮回调)
          // console.log(items[0].startDate);
          _This.startDate = items[0].startDate;
          _This.endDate = items[0].endDate;
          let params = {
            page:1,
            pageSize:2,
            indexSubscriptionId:_This.ids,
            startDate:_This.startDate,
            endDate:_This.endDate,
            extendInfo:true
          };
          _This.slideAjax(params,function (data) {
            _This.radarChart(data[0].id);   //雷达图
            _This.postMatfeaturesData(data[0].id);  //主材特征
            _This.postContentData(data[0].id);  //主材含量
          })
        });
      }

    },
    lineChart:function(){  //折线图
      let _This = this;
      let echartDom = document.getElementById('detailEchart');
      if(echartDom == null) return;
      _This.LineChart = _This.$echarts.init(echartDom);
      let xAxisData = [];
      let seriesData = [];
      let indexCode = this.$route.query.indexCode;
      let indexType = this.$route.query.indexType;
      let params = {  //接收首页参数
        indexCode:indexCode,
        indexType:indexType,
        showType:4
      };
      // 绘制图表
      _This.FnAxiosAjax('post','/api/indexIntegration/trend',params,function (data) {
        // console.log(data);
        _This.contentTitle = data.results.indexInfo.indexName;
        let lineData = data.results.lineData;
        if(lineData == '' || lineData == null){
          _This.noDataShow[0] = false;
        }
        for(let i=0;i<lineData.length;i++){
          let timeData = '';
          let chartTimeData = '';
          let monthDate = '';
          let years = lineData[i].name.toString().substring(0,4);  //切割年份
          let moons = lineData[i].name.toString().substring(lineData[i].name.toString().length-2);  //切割月份
          let parseNum = parseFloat(moons);  //转化为数字类型
          if(parseNum<4){
            timeData = years+'年' + '第一季度';
            chartTimeData = years+'年' + 'Q1';
            monthDate = 1;
          }else if(3<parseNum && parseNum<7){
            timeData = years+'年' + '第二季度';
            chartTimeData = years+'年' + 'Q2';
            monthDate = 4;
          }else if(6<parseNum && parseNum<10){
            timeData = years+'年' + '第三季度';
            chartTimeData = years+'年' + 'Q3';
            monthDate = 7;
          }else if(9<parseNum && parseNum<13){
            timeData = years+'年' + '第四季度';
            chartTimeData = years+'年' + 'Q4';
            monthDate = 10;
          }
          // _This.startDate = new Date(years,monthDate);
          // _This.endDate = new Date(years,monthDate+2);
          _This.startDate = _This.crtTimeFtt(years,monthDate);
          _This.endDate = _This.crtTimeFtt(years,monthDate+2);
          _This.chooseDateArr.push(   //日期数组
            {
              startDate:_This.startDate,
              endDate:_This.endDate,
              text:timeData
            }
          );
          xAxisData.push(chartTimeData);
          seriesData.push(lineData[i].value.toFixed(2));
        }
        _This.LineChart.setOption({
          tooltip: {
            trigger: 'axis'
          },
          grid: {
            left: 0,
            right: 0,
            top:'10%',
            bottom: 0,
            containLabel: true
          },
          color:['#fff'],
          xAxis: {
            type: 'category',
            splitLine: false,
            axisLine:false,
            axisLabel:{
              textStyle:{
                color:'#fff',
              }
            },
            axisTick:false,
            data: xAxisData
          },
          yAxis: {
            type: 'value',
            splitLine: false,
            axisLine:false,
            axisLabel:false,
            axisTick:false
          },
          series: [{
            data: seriesData,
            type: 'line',
            smooth: true
          }]
        });
        window.addEventListener("resize",_This.chartResize); //图表自适应
        //加载曲线图数据后再加载其他数据
        _This.postSlideData(function (data) {  //选择滑块数据
            _This.subStatus = data[0].subStatus;  //顶部收藏状态
            _This.radarChart(data[0].id);   //雷达图
            _This.postMatfeaturesData(data[0].id);  //主材特征
            _This.postContentData(data[0].id);  //主材含量
            _This.synId = data[0].id;   //初始化时指标id
            setTimeout(() => {
              var mySwiper = new Swiper ('.swiper-container', {
                spaceBetween: 10, //间隙
                slidesPerView: 'auto',
                observer:true,//修改swiper自己或子元素时，自动初始化swiper
                observeParents:true,//修改swiper的父元素时，自动初始化swiper
                on: {
                  touchEnd:function () {   //切换到最后一个Slide时执行
                    _This.swiperTouch()
                  }
                },
              });
            },200)
        });
      })
    },
    radarChart:function (id) {  //雷达图
      let _This = this;
      // 基于准备好的dom，初始化echarts图表
      let echartDom = document.getElementById('radarEchart');
      if(echartDom == null) return;
      _This.raChart = this.$echarts.init(echartDom);
      let indicatorData = [];
      let seriesData = [];
      let seriesName = [];
      let params = {
        integrationId:id
      };
      _This.FnAxiosAjax('post','/api/matfeatures/getProjectFeatures',params,function (data) {
        _This.radarData = data.results;
        if(_This.radarData == '' || _This.radarData == null){
          _This.noDataShow[1] = false;
          return '';
        }
        for(let i=0;i<_This.radarData.length;i++){
          let nextName = textLengthFormatter(_This.radarData[i].nextName);
          indicatorData.push({name:nextName,max:1});
          seriesData.push(_This.radarData[i].percent);
          // seriesName.push(nextName);
        }
        _This.raChart.setOption({
          tooltip: {
            trigger: 'item',
            position: ['50%', '70%'],
            confine:true,  //始终显示在图表内
            // formatter:function (params) {
            //   return params.name+params.value
            // }
          },
          radar: {
            // shape: 'circle',
            radius:60,   //半径
            center:['50%','50%'], // 图的位置
            splitArea : {
              show : false,
              areaStyle : {
                color: ["#f8f8f8","#e9e9e9"]  // 图表背景网格区域的颜色
              }
            },
            name: {
              textStyle: {
                color: '#666',
                padding: [-10, 0]
              }
            },
            indicator: indicatorData
            // [
            // { name: '围护结构', max: 6500},
            // { name: '主体结构', max: 16000},
            // { name: '土石方', max: 30000}
            // ]
          },
          series: [{
            name: '工程特征',
            type: 'radar',
            areaStyle: {
              color:['rgba(232,77,99,0.3)']
            },
            data : [
              {
                value : seriesData,
                // name: seriesName
              }
            ]
          }]
        });
        window.addEventListener("resize",_This.chartResize); //图表自适应
      });
    },
    postMatfeaturesData:function (integrationId) {   //主材特征
      let _This = this;
      let params = {
        integrationId:integrationId,
        page:_This.featuresPage,
        pageSize:5,
        collected:true
      };
      _This.featuresAjax(params,function (data) {
        // console.log(data);
        _This.materialsData = data;
        if(_This.materialsData == '' || _This.materialsData == null){
          _This.noDataShow[2] = false;
        }
      })
    },
    postContentData:function (id) {  //主材含量
      let _This = this;
      let params = {
        integrationId:id,
        page:_This.contentPage,
        pageSize:5
      };
      _This.contentAjax(params,function (data) {
        _This.contentData = data;
        // console.log(_This.contentData);
        if(_This.contentData == '' || _This.contentData == null){
          _This.noDataShow[3] = false;
        }
      })
    },
    back:function () {
      // this.$router.back(-1);
      this.$router.push({path: 'index'});
    },
    topCollect: function(){    //顶部收藏
      let _This = this;
      _This.subStatus = !_This.subStatus;
      let params = {
        ids:_This.synId,  //综合指标id
      };
      if( _This.subStatus == true){
        _This.topCollectAjax(params,function () {  //发送请求
          mui.confirm('收藏成功','提示',['确定'],function (e) {   //提示弹窗

          })
        })
      }else {
        _This.topCollectAjax(params,function () {  //发送请求
          mui.confirm('取消收藏','提示',['确定'],function (e) {   //提示弹窗

          })
        })
      }
    },
    collect:function (item) {  //主材特征收藏
      let _This = this;
      item.collected = !item.collected;
      let params = {
        integrationId:item.integrationId,  //综合指标id
        mainMatId:item.id,  //主材id
        collected:item.collected  //收藏
      };
      _This.FnAxiosAjax( 'post','/api/matfeatures/matcollect',params,function (data) {
        _This.fangerroring = true;  //提示
        _This.fangerrorText = data.msg;
        _This.setTimeoutError();
      })
    },
    lookFeature:function (id) {  //主材特征查看
      this.$router.push({path: 'detaiFeaturel?id='+id});  //传id
    },
    //上拉加载更多(主材特征)
    featuresInfinite(done) {
      let _This = this;
      if(this.noData) {
        setTimeout(() => {
          _This.$refs.indexsublist.finishInfinite(2);
        });
        return;
      }
      setTimeout(() => {
        _This.$nextTick(()=>{
          if(_This.featuresLength > 5){
            _This.featuresPage =  _This.featuresPage + 1;
            let params = {
              integrationId:_This.synId,
              page:_This.featuresPage,
              pageSize:5,
              collected:true
            };
            _This.featuresAjax(params,function (data) {   //上拉时发送请求
              if(data=='' || data == null){
                done(true);//没有更多数据
              }else {
                done();
              }
              if(_This.materialsData == ''){
                _This.materialsData = data;
              }else {
                for(let key in data){
                  _This.materialsData.push(data[key]);
                }
              }
            });
          }
        })
      }, 500)
      //回调选中数据 specialtyCode,indexType,parent,page,pageSize,fn

    },
    //上拉加载更多(主材含量)
    contentInfinite(done) {
      let _This = this;
      if(this.noData) {
        setTimeout(() => {
          _This.$refs.indexsublist.finishInfinite(2);
        });
        return;
      }
      setTimeout(() => {
        _This.$nextTick(()=>{
          if(_This.contentLength > 5){
            _This.contentPage =  _This.contentPage + 1;
            let params = {
              integrationId:_This.synId,
              page:_This.contentPage,
              pageSize:5,
            };
            _This.featuresAjax(params,function (data) {   //上拉时发送请求
              if(data=='' || data == null){
                done(true);//没有更多数据
              }else {
                done();
              }
              if(_This.contentData == ''){
                _This.contentData = data;
              }else {
                for(let key in data){
                  _This.contentData.push(data[key]);
                }
              }
            });
          }
        })
      }, 500)
      //回调选中数据 specialtyCode,indexType,parent,page,pageSize,fn

    },
    featuresAjax:function (params,fn) {
      let _This = this;
      _This.FnAxiosAjax('post','/api/matfeatures/list',params,function (data) {
        !! fn && fn(data.results);
        _This.featuresLength = data.totalCount;  //所有条数
      })
    },
    contentAjax:function (params,fn) {
      let _This = this;
      _This.FnAxiosAjax('post','/api/matfeatures/list',params,function (data) {
        !! fn && fn(data.results);
        _This.contentLength = data.totalCount;   //数据总条数
      })
    },
    topCollectAjax:function (params,fn) {
      this.FnAxiosAjax('post','/api/indexIntegration/subscription',params,function (data) {
        !! fn && fn(data);
      })
    },
    slideAjax:function (params,fn) {
      let _This = this;
      _This.FnAxiosAjax('post','/api/indexIntegration/querybysubscriptionid',params,function (data) {
        fn(data.results);
        _This.slideArr = data;
      })
    },
    crtTimeFtt:function (year, month) {
      if (year != null || month != null) {
        let date = new Date(year,month);
        return date.getFullYear() + '-' + (date.getMonth());
      }
    },
    clickSwiper:function (id,subStatus) {  //点击swiper获取下面的内容
      let _This = this;
      _This.synId = id;   //综合指标id
      _This.subStatus = subStatus;  //顶部收藏状态
      _This.featuresPage = 1;  //页面重新初始化
      _This.contentPage = 1;
      _This.radarChart(id);   //雷达图
      _This.postMatfeaturesData(id);  //主材特征
      _This.postContentData(id);  //主材含量
    },
    swiperTouch:function () {
      let _This = this;
      let $slide = $('.swiper-slide');
      let SlideWidth=$slide.eq(0).width();
      let swiperWidthR=SlideWidth*($slide.length-1)+20;
      let TR = $('.swiper-wrapper').css('transform').split(',')[4];
      TR = Number(TR);
      let foolNum = Math.ceil(_This.slideArr.totalCount);  //数据总条数
      if(TR<-swiperWidthR){
        if(_This.slidePage == foolNum) {   //是否是最后一个
          _This.fangerroring = true;  //提示
          _This.fangerrorText = '已经没有啦！';
          _This.setTimeoutError();
          return;
        }
        _This.slidePage = _This.slidePage + 1;
        _This.fangerroring = true;
        let params = {
          page:_This.slidePage,
          pageSize:1,
          indexSubscriptionId:_This.ids,
          extendInfo:true
        };
        _This.slideAjax(params,function (datas) {
          _This.fangerroring = false;
          for (let key in datas) {
            _This.slideData.push(datas[key]);
          }
        })
      }
    },
    // lookContent:function (integrationId) {  //主材含量查看
    //   this.$router.push({path: 'detailContent?id='+integrationId});
    // },
  },
}
